<template>
  <a-card style="width: 100%">
    <div class="header">
      <a-space class="left" direction="vertical" :size="[8, 12]">
        <Condition
          :condition="condition"
          :btns="['reset']"
          @search="onSearch"
          @reset="conditionReset"
        ></Condition>
        <div class="title">共筛选出 {{ pagination.total }} 条数据</div>
      </a-space>
      <a-space class="right" direction="vertical" :size="[8, 12]">
        <a-input-search
          v-model:value="templateName"
          placeholder="请输入饮食方案名称"
          style="width: 220px"
          @search="onSearch"
        />
        <a-button type="primary" @click="modalShow('')">新建饮食方案</a-button>
      </a-space>
    </div>
    <div class="main">
      <a-table
        class="table"
        size="small"
        :loading="loading"
        :dataSource="List"
        :columns="columns"
        :pagination="pagination"
        @change="paginationChange"
        :sticky="{ offsetHeader: 0 }"
      >
        <template #bodyCell="{ column, text, index, record }">
          <template v-if="column.dataIndex === 'no'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ timeFilter(record[column.dataIndex]) }}
          </template>
          <template v-else-if="column.dataIndex === 'managePath'">
            <div class="tags" v-if="record[column.dataIndex]">
              <a-tag
                type="parmary"
                :title="item"
                v-for="(item, i) in record[column.dataIndex].split(', ')"
                :key="i"
                >{{ item }}</a-tag
              >
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" @click="modalShow(record)">查看详情</a-button>
            <a-button
              type="link"
              @click="delForm(record)"
              :disabled="record.managePath ? true : false"
              >删除方案</a-button
            >
          </template>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      width="720px"
      v-model:open="modal.open"
      :title="modal.title"
      ok-text="确认"
      cancel-text="取消"
      @ok="modalConfirm"
      :maskClosable="false"
      :body-style="{ maxHeight: '540px', overflow: 'hidden auto' }"
    >
      <a-form
        class="modelForm"
        ref="modelForm"
        :colon="false"
        :model="formState"
        :label-col="{ style: { width: '110px' } }"
        :disabled="modal.type === 'detail'"
        labelAlign="left"
      >
        <a-form-item
          label="模板类型"
          name="templateAffiliation"
          required
          v-if="modal.type != 'detail' && !formState.id"
        >
          <a-select v-model:value="formState.templateAffiliation">
            <a-select-option label="公共模板" value="公共模板"> 公共模板 </a-select-option>
            <a-select-option label="个人模板" value="个人模板"> 个人模板 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="饮食方案名称"
          name="templateName"
          required
          :rules="{
            required: true,
            message: '饮食方案名称不能为空',
            trigger: 'change'
          }"
        >
          <a-tooltip
            v-if="modal.type === 'detail'"
            placement="bottomLeft"
            :title="formState.templateName"
          >
            <a-input
              style="width: 350px"
              v-model:value="formState.templateName"
              autocomplete="off"
              placeholder="请输入饮食方案名称"
              :maxlength="50"
            ></a-input>
          </a-tooltip>
          <a-input
            v-else
            style="width: 350px"
            v-model:value="formState.templateName"
            autocomplete="off"
            :maxlength="50"
            placeholder="请输入饮食方案名称"
          ></a-input>
        </a-form-item>
        <a-form-item required label="饮食方案内容:"> </a-form-item>
        <div>
          <div class="season-row">
            <span
              :class="['season-item', secindex === seasonKey ? 'season-item-active' : '']"
              v-for="(seasonItem, secindex) in formState.content.seasons"
              :key="secindex"
              @click="seasonChange(secindex)"
            >
              {{ seasonLabel[seasonItem.season] }}
            </span>
          </div>

          <div class="week-row">
            <div
              v-for="(weekItem, weekIndex) in formState.content.seasons[seasonKey].week"
              :key="weekIndex"
            >
              <span
                @click="weekChange(weekIndex)"
                :class="['week-item', weekIndex === activeKey ? 'week-item-active' : '']"
              >
                {{ weekLabel[weekItem.day - 1] }}食谱
              </span>
              <a-divider
                style="margin-right: 13px"
                v-if="weekIndex !== formState.content.seasons[seasonKey].week.length - 1"
                type="vertical"
              />
            </div>
          </div>

          <div>
            <p class="diet-info-box">
              食谱详情：
              <span class="diet-info diet-all">总摄入{{ getFoodInfo('energy') }}千卡 </span>
              <span class="diet-info">碳水{{ getFoodInfo('cho') }}g</span>
              <span class="diet-info">蛋白质{{ getFoodInfo('pro') }}g</span>
              <span class="diet-info">脂肪{{ getFoodInfo('fat') }}g</span>
            </p>

            <a-form-item label="早餐" :labelCol="{ style: { width: '60px' } }" required>
              <div class="dict-group">
                <div
                  class="dict-name"
                  v-for="(diet, dietIndex) in formState.content.seasons[seasonKey].week[activeKey]
                    .itemContent.breakfast.food_items"
                  :key="dietIndex"
                >
                  <span>
                    {{ diet.name }}
                    <span
                      class="food-sub-name"
                      v-for="(subDiet, subDietIndex) in diet.ingredients"
                      :key="subDietIndex"
                    >
                      （
                      {{ subDiet.name }}
                      <span
                        class="food-weight"
                        @click="showDict('breakfast', 'edit', dietIndex, subDietIndex)"
                      >
                        {{ subDiet.amount }}
                      </span>
                      g）
                    </span>
                  </span>

                  <CloseOutlined
                    class="dict-del-icon"
                    @click="delDict('breakfast', dietIndex)"
                    v-if="modal.type !== 'detail'"
                  />
                </div>
                <div
                  class="dict-btn"
                  @click="showDict('breakfast', 'add')"
                  v-if="modal.type !== 'detail'"
                >
                  新增
                  <PlusOutlined class="icon-add" />
                </div>
              </div>
            </a-form-item>

            <a-form-item label="早加餐" :labelCol="{ style: { width: '60px' } }">
              <div class="dict-group">
                <div
                  class="dict-name"
                  v-for="(diet, dietIndex) in formState.content.seasons[seasonKey].week[activeKey]
                    .itemContent.breakfast_plus.food_items"
                  :key="dietIndex"
                >
                  <span>
                    {{ diet.name }}
                    <span
                      class="food-sub-name"
                      v-for="(subDiet, subDietIndex) in diet.ingredients"
                      :key="subDietIndex"
                    >
                      （
                      {{ subDiet.name }}
                      <span
                        class="food-weight"
                        @click="showDict('breakfast_plus', 'edit', dietIndex, subDietIndex)"
                      >
                        {{ subDiet.amount }}
                      </span>
                      g）
                    </span>
                  </span>

                  <CloseOutlined
                    class="dict-del-icon"
                    @click="delDict('breakfast_plus', dietIndex)"
                    v-if="modal.type !== 'detail'"
                  />
                </div>
                <span
                  class="dict-btn"
                  @click="showDict('breakfast_plus', 'add')"
                  v-if="modal.type !== 'detail'"
                >
                  新增
                  <PlusOutlined class="icon-add" />
                </span>
              </div>
            </a-form-item>

            <a-form-item label="午餐" :labelCol="{ style: { width: '60px' } }" required>
              <div class="dict-group">
                <div
                  class="dict-name"
                  v-for="(diet, dietIndex) in formState.content.seasons[seasonKey].week[activeKey]
                    .itemContent.lunch.food_items"
                  :key="dietIndex"
                >
                  <span>
                    {{ diet.name }}
                    <span
                      class="food-sub-name"
                      v-for="(subDiet, subDietIndex) in diet.ingredients"
                      :key="subDietIndex"
                    >
                      （
                      {{ subDiet.name }}
                      <span
                        class="food-weight"
                        @click="showDict('lunch', 'edit', dietIndex, subDietIndex)"
                      >
                        {{ subDiet.amount }}
                      </span>
                      g）
                    </span>
                  </span>

                  <CloseOutlined
                    class="dict-del-icon"
                    @click="delDict('lunch', dietIndex)"
                    v-if="modal.type !== 'detail'"
                  />
                </div>
                <span
                  class="dict-btn"
                  @click="showDict('lunch', 'add')"
                  v-if="modal.type !== 'detail'"
                >
                  新增
                  <PlusOutlined class="icon-add" />
                </span>
              </div>
            </a-form-item>

            <a-form-item label="午加餐" :labelCol="{ style: { width: '60px' } }">
              <div class="dict-group">
                <div
                  class="dict-name"
                  v-for="(diet, dietIndex) in formState.content.seasons[seasonKey].week[activeKey]
                    .itemContent.lunch_plus.food_items"
                  :key="dietIndex"
                >
                  <span>
                    {{ diet.name }}
                    <span
                      class="food-sub-name"
                      v-for="(subDiet, subDietIndex) in diet.ingredients"
                      :key="subDietIndex"
                    >
                      （
                      {{ subDiet.name }}
                      <span
                        class="food-weight"
                        @click="showDict('lunch_plus', 'edit', dietIndex, subDietIndex)"
                      >
                        {{ subDiet.amount }}
                      </span>
                      g）
                    </span>
                  </span>

                  <CloseOutlined
                    class="dict-del-icon"
                    @click="delDict('lunch_plus', dietIndex)"
                    v-if="modal.type !== 'detail'"
                  />
                </div>
                <span
                  class="dict-btn"
                  @click="showDict('lunch_plus', 'add')"
                  v-if="modal.type !== 'detail'"
                >
                  新增
                  <PlusOutlined class="icon-add" />
                </span>
              </div>
            </a-form-item>

            <a-form-item label="晚餐" :labelCol="{ style: { width: '60px' } }" required>
              <div class="dict-group">
                <div
                  class="dict-name"
                  v-for="(diet, dietIndex) in formState.content.seasons[seasonKey].week[activeKey]
                    .itemContent.dinner.food_items"
                  :key="dietIndex"
                >
                  <span>
                    {{ diet.name }}
                    <span
                      class="food-sub-name"
                      v-for="(subDiet, subDietIndex) in diet.ingredients"
                      :key="subDietIndex"
                    >
                      （
                      {{ subDiet.name }}
                      <span
                        class="food-weight"
                        @click="showDict('dinner', 'edit', dietIndex, subDietIndex)"
                      >
                        {{ subDiet.amount }}
                      </span>
                      g）
                    </span>
                  </span>

                  <CloseOutlined
                    class="dict-del-icon"
                    @click="delDict('dinner', dietIndex)"
                    v-if="modal.type !== 'detail'"
                  />
                </div>
                <span
                  class="dict-btn"
                  @click="showDict('dinner', 'add')"
                  v-if="modal.type !== 'detail'"
                >
                  新增
                  <PlusOutlined class="icon-add" />
                </span>
              </div>
            </a-form-item>

            <a-form-item label="晚加餐" :labelCol="{ style: { width: '60px' } }">
              <div class="dict-group">
                <div
                  class="dict-name"
                  v-for="(diet, dietIndex) in formState.content.seasons[seasonKey].week[activeKey]
                    .itemContent.dinner_plus.food_items"
                  :key="dietIndex"
                >
                  <span>
                    {{ diet.name }}
                    <span
                      class="food-sub-name"
                      v-for="(subDiet, subDietIndex) in diet.ingredients"
                      :key="subDietIndex"
                    >
                      （
                      {{ subDiet.name }}
                      <span
                        class="food-weight"
                        @click="showDict('dinner_plus', 'edit', dietIndex, subDietIndex)"
                      >
                        {{ subDiet.amount }}
                      </span>
                      g）
                    </span>
                  </span>

                  <CloseOutlined
                    class="dict-del-icon"
                    @click="delDict('dinner_plus', dietIndex)"
                    v-if="modal.type !== 'detail'"
                  />
                </div>
                <span
                  class="dict-btn"
                  @click="showDict('dinner_plus', 'add')"
                  v-if="modal.type !== 'detail'"
                >
                  新增
                  <PlusOutlined class="icon-add" />
                </span>
              </div>
            </a-form-item>
          </div>
        </div>
      </a-form>
      <template #footer>
        <template v-if="modal.type !== 'detail'">
          <a-button
            @click="
              () => {
                ;(modal.open = false), modelForm.clearValidate()
              }
            "
            >取消</a-button
          >
          <a-button :loading="modal.loading" type="primary" @click="modalConfirm">确认</a-button>
        </template>
        <template v-else>
          <a-button @click="modalUpdate" :disabled="!modal.allowUpdate">编辑</a-button>
          <a-button type="primary" @click="modal.open = false">确认</a-button>
        </template>
      </template>
    </a-modal>

    <!-- 选择食谱 -->
    <a-modal
      width="720px"
      v-model:open="dietOpen"
      :title="!dietFormDisable ? '添加食物' : '修改食物'"
      :maskClosable="false"
      ok-text="确认"
      cancel-text="取消"
    >
      <a-form :label-col="{ style: { width: '80px' } }" :model="dietForm" ref="dietFormRef">
        <a-form-item label="选择食物" name="foodName" required>
          <a-select
            v-model:value="dietForm.foodName"
            showSearch
            :options="dietDictData"
            style="width: 100%"
            placeholder="食物名称"
            :listHeight="200"
            allowClear
            :disabled="dietFormDisable"
            @change="dietChange"
            option-label-prop="label"
          >
            <template #option="{ label, energy, cho, fat, pro }">
              {{ label }}
              <span v-if="energy || cho || pro || fat" style="color: #666; font-size: 12px">
                每100克：热量{{ energy }}千卡、碳水{{ cho }}克、蛋白质{{ pro }}克、脂肪{{ fat }}克
              </span>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="食物重量" name="amount" required>
          <div style="display: flex; align-items: center; justify-content: space-between">
            <a-input-number
              v-model:value="dietForm.amount"
              :min="0"
              step="0.1"
              :precision="1"
              style="width: 100%"
            />
          </div>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button
          @click="
            () => {
              ;(dietOpen = false), dietFormRef.clearValidate()
            }
          "
        >
          取消
        </a-button>
        <a-button type="primary" @click="dietConfirm">确认</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script lang="ts" setup name="饮食方案">
import { ref, reactive, onMounted, unref, nextTick } from 'vue'
import Condition from '@/components/Condition/index.vue'
import { createVNode } from 'vue'
import { getTemplateList, TemplateAdd, TemplateUpdate, TemplateDel } from '@/api/template'
import { ExclamationCircleFilled, PlusOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useDict } from './components/getDict'
import { timeFilter } from '@/utils/tools'
import _ from 'lodash'
import store from '@/store'

const seasonLabel = reactive<any>({
  spring: '春季',
  summer: '夏季',
  fall: '秋季',
  winter: '冬季'
})
const weekLabel = reactive<any>(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
const templateType = '饮食方案'
const templateName = ref('')
const dietOpen = ref<boolean>(false)
const activeKey = ref(0)
const seasonKey = ref(0)

const dietFormRef = ref()
const dietForm = reactive({
  foodName: '',
  amount: undefined,
  energy: undefined,
  cho: undefined,
  pro: undefined,
  fat: undefined
})

let { creatorList, manageList, init } = useDict(templateType)

const formState_reset = (item) => {
  if (item) {
    Object.assign(formState, item)
  } else {
    Object.assign(formState, {
      id: '',
      templateName: '',
      templateType: templateType,
      content: {
        seasons: [
          {
            season: 'spring',
            week: [
              {
                day: 1,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 2,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 3,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 4,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 5,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 6,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 7,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              }
            ]
          },
          {
            season: 'summer',
            week: [
              {
                day: 1,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 2,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 3,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 4,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 5,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 6,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 7,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              }
            ]
          },
          {
            season: 'fall',
            week: [
              {
                day: 1,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 2,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 3,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 4,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 5,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 6,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 7,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              }
            ]
          },
          {
            season: 'winter',
            week: [
              {
                day: 1,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 2,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 3,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 4,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 5,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 6,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              },
              {
                day: 7,
                itemContent: {
                  breakfast: {
                    food_items: []
                  },
                  breakfast_plus: {
                    food_items: []
                  },
                  lunch: {
                    food_items: []
                  },
                  lunch_plus: {
                    food_items: []
                  },
                  dinner: {
                    food_items: []
                  },
                  dinner_plus: {
                    food_items: []
                  }
                }
              }
            ]
          }
        ]
      },
      templateAffiliation: '公共模板'
    })
  }
}

const formState = reactive({
  id: '',
  templateName: '',
  templateType: templateType,
  content: {
    seasons: []
  },
  templateAffiliation: '公共模板'
})

const condition = ref([
  {
    title: '创建者',
    dataIndex: 'creator',
    type: 'select',
    value: '',
    data: creatorList
  },
  {
    title: '已配置管理路径',
    dataIndex: 'manageId',
    type: 'select',
    value: '',
    data: manageList
  },
  {
    title: '模板类型',
    dataIndex: 'templateAffiliation',
    type: 'select',
    value: '',
    data: [
      {
        value: '',
        label: '全部'
      },
      {
        value: '公共模板',
        label: '公共模板'
      },
      {
        value: '个人模板',
        label: '个人模板'
      }
    ]
  }
])

const conditionReset = () => {
  pagination.current = 1
  init()
  condition.value.map((v) => {
    v.value = ''
  })
  getList()
}

const pagination = reactive({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: '50px'
  },
  {
    title: '饮食方案名称',
    dataIndex: 'templateName',
    key: 'templateName',
    align: 'left',
    minWidth: 100
  },
  {
    title: '模板类型',
    dataIndex: 'templateAffiliation',
    key: 'templateAffiliation',
    align: 'left',
    width: 100
  },
  {
    title: '已配置管理路径',
    dataIndex: 'managePath',
    key: 'managePath',
    align: 'left',
    minWidth: 200,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'left',
    width: '140px'
  },
  {
    title: '创建者',
    dataIndex: 'creator',
    key: 'creator',
    align: 'left',
    widht: '80px'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: '200px'
  }
])

const loading = ref(false)
const List = ref([])

const getList = () => {
  loading.value = true
  const { current, pageSize } = pagination
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0) {
      return Object.assign(c, { [v.dataIndex]: v.value })
    } else {
      return c
    }
  }, {})
  const params = {
    page: current,
    limit: pageSize,
    templateName: templateName.value,
    templateType: templateType,
    ...obj
  }
  getTemplateList(params)
    .then((res) => {
      loading.value = false
      if (res.data.total > 0 && !res.data.list.length) {
        pagination.current = pagination.current - 1
        getList()
      } else {
        pagination.total = res.data.total
        List.value = res.data.list
      }
    })
    .catch((e) => {
      loading.value = false
    })
}

const paginationChange = (p) => {
  Object.assign(pagination, p)
  getList()
}

const onSearch = () => {
  pagination.current = 1
  getList()
}

const dietDictData: any = ref()
onMounted(() => {
  getList()
  dietDictData.value = JSON.parse(sessionStorage.getItem('dietDictData'))
})

const modal = reactive({
  open: false,
  type: 'save',
  loading: false,
  allowUpdate: true,
  title: '新建饮食方案'
})

const modelForm = ref(null)

const modalShow = (item) => {
  modelForm.value?.clearValidate()
  formState_reset(null)
  activeKey.value = 0
  seasonKey.value = 0
  if (item) {
    modal.title = '饮食方案详情'
    modal.type = 'detail'
    const { id, templateName, content, managePath, templateAffiliation } = _.cloneDeep(item)
    formState_reset({
      id,
      templateName,
      templateType,
      content: JSON.parse(content),
      templateAffiliation
    })

    modal.allowUpdate = managePath ? false : true
    modal.open = true
  } else {
    modal.title = '新建饮食方案'
    modal.type = 'save'
    formState_reset(null)
    modal.allowUpdate = true
    modal.open = true
  }
}

const modalConfirm = () => {
  modelForm.value
    .validate()
    .then(() => {
      try {
        formState.content.seasons.forEach((item) => {
          item.week.forEach((vo) => {
            if (!vo.itemContent.breakfast.food_items.length) {
              message.error(`请选择食物`)
              throw Error()
            }

            if (!vo.itemContent.lunch.food_items.length) {
              message.error(`请选择食物`)
              throw Error()
            }

            if (!vo.itemContent.dinner.food_items.length) {
              message.error(`请选择食物`)
              throw Error()
            }
          })
        })
      } catch {
        return
      }

      const params = {
        ...formState,
        content: JSON.stringify(formState.content),
        platformId: store.userStore.platformId
      }

      modal.loading = true
      if (modal.type === 'save') {
        TemplateAdd(params)
          .then((res) => {
            modal.loading = false
            message.success('新建成功')
            conditionReset()
            modal.open = false
          })
          .catch((e) => {
            modal.loading = false
          })
      } else {
        TemplateUpdate(params)
          .then((res) => {
            modal.loading = false
            message.success('编辑成功')
            init()
            getList()
            modal.open = false
          })
          .catch((e) => {
            modal.loading = false
          })
      }
    })
    .catch((e) => {
      modal.loading = false
      message.error(e.errorFields[0].errors[0])
      // 表单校验失败
      modelForm.value.scrollToField(e.errorFields[0].name, {
        behavior: 'smooth',
        block: 'center'
      })
    })
}

const modalUpdate = () => {
  modal.type = 'update'
  modal.title = '编辑饮食方案'
}

const delForm = (item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确定删除该方案么',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      TemplateDel(item.id).then(() => {
        message.success('删除成功')
        init()
        getList()
      })
    },
    onCancel() {}
  })
}

const addFoodType = ref('')
const dietFormDisable = ref(false)
const dietDayIndex = ref<any>()
const ingredientsIndex = ref<any>()
const showDict = (foodType: any, handleType: string, dietIndex?: any, subDietIndex?: any) => {
  dietFormDisable.value = handleType === 'edit' ? true : false
  addFoodType.value = foodType
  if (modal.type != 'detail') {
    dietOpen.value = true
    nextTick(() => {
      if (dietFormRef.value) {
        dietForm.foodName = ''
        dietForm.amount = undefined
        dietForm.energy = undefined
        dietForm.cho = undefined
        dietForm.pro = undefined
        dietForm.fat = undefined
        dietDayIndex.value = dietIndex
        ingredientsIndex.value = subDietIndex
        if (dietIndex != undefined || dietIndex != null) {
          const diet =
            formState.content.seasons[seasonKey.value].week[activeKey.value].itemContent[foodType]
              .food_items[dietIndex].ingredients[subDietIndex]
          dietForm.foodName = diet.name
          dietForm.amount = diet.amount
          dietForm.energy = diet.energy
          dietForm.cho = diet.cho
          dietForm.pro = diet.pro
          dietForm.fat = diet.fat
        }
      }
    })
  }
}

// 删除
const delDict = (foodType: any, dietIndex: any) => {
  formState.content.seasons[seasonKey.value].week[activeKey.value].itemContent[
    foodType
  ].food_items.splice(dietIndex, 1)
}

// 食物选择
const dietChange = (item: any) => {
  dietDictData.value.map((vo: any) => {
    if (vo.options) {
      const selectDietData = vo.options.find((child: any) => child.label === item)
      if (selectDietData) {
        dietForm.foodName = selectDietData.label
        dietForm.energy = selectDietData.energy
        dietForm.cho = selectDietData.cho
        dietForm.pro = selectDietData.pro
        dietForm.fat = selectDietData.fat
      }
    }
  })
}

//
const dietConfirm = () => {
  dietFormRef.value
    .validate()
    .then(() => {
      if (dietFormDisable.value) {
        formState.content.seasons[seasonKey.value].week[activeKey.value].itemContent[
          addFoodType.value
        ].food_items[dietDayIndex.value].ingredients[ingredientsIndex.value] = {
          name: dietForm.foodName,
          amount: dietForm.amount,
          energy: dietForm.energy,
          cho: dietForm.cho,
          pro: dietForm.pro,
          fat: dietForm.fat
        }
      } else {
        formState.content.seasons[seasonKey.value].week[activeKey.value].itemContent[
          addFoodType.value
        ].food_items.push({
          name: dietForm.foodName,
          ingredients: [
            {
              name: dietForm.foodName,
              amount: dietForm.amount,
              energy: dietForm.energy,
              cho: dietForm.cho,
              pro: dietForm.pro,
              fat: dietForm.fat
            }
          ]
        })
      }

      dietOpen.value = false
    })
    .catch((e) => {
      //
    })
}

// 四季切换
const seasonChange = (index: any) => {
  seasonKey.value = index
  activeKey.value = 0
}

// 星期切换
const weekChange = (index: any) => {
  activeKey.value = index
}

// 能量统计
const getFoodInfo = (type: any) => {
  const data: any = formState.content.seasons[seasonKey.value].week[activeKey.value].itemContent
  let total: any = 0
  data.breakfast.food_items.forEach((item) => {
    item.ingredients.forEach((child) => {
      if (child[type]) {
        total += (Number(child[type]) / 100) * Number(child.amount)
      }
    })
  })

  data.lunch.food_items.forEach((item) => {
    item.ingredients.forEach((child) => {
      if (child[type]) {
        total += (Number(child[type]) / 100) * Number(child.amount)
      }
    })
  })

  data.dinner.food_items.forEach((item) => {
    item.ingredients.forEach((child) => {
      if (child[type]) {
        total += (Number(child[type]) / 100) * Number(child.amount)
      }
    })
  })

  data.breakfast_plus.food_items.forEach((item) => {
    item.ingredients.forEach((child) => {
      if (child[type]) {
        total += (Number(child[type]) / 100) * Number(child.amount)
      }
    })
  })

  data.lunch_plus.food_items.forEach((item) => {
    item.ingredients.forEach((child) => {
      if (child[type]) {
        total += (Number(child[type]) / 100) * Number(child.amount)
      }
    })
  })

  data.dinner_plus.food_items.forEach((item) => {
    item.ingredients.forEach((child) => {
      if (child[type]) {
        total += (Number(child[type]) / 100) * Number(child.amount)
      }
    })
  })

  return total ? total.toFixed(1) : '--'
}
</script>

<style lang="less" scoped>
@import './index.less';

.header {
  flex: 0 0 auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .left {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    .title {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 400;
      color: #4e5969;
      line-height: 32px;
    }
  }

  .right {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
    }
  }
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;

  :deep(.ant-table-wrapper) {
    .ant-table-cell {
      p {
        white-space: normal;
        margin-bottom: 0;

        .configuration {
          color: #3491fa;
          background: #e8f7ff;
          border-color: #3491fa;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;

          &:nth-child(1) {
            margin-top: 0;
          }
        }

        .success {
          color: #00b42a;
          background: #e8ffea;
          border-color: #00b42a;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;

          &:nth-child(1) {
            margin-top: 0;
          }
        }
        .groupTag {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          margin-right: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
      }
    }
  }
}

.input {
  width: 210px !important;
}

.ant-form .ant-input {
  width: 100% !important;
}

.dict-group {
  padding: 0 4px;
  border: 1px solid #d9d9d9;
  min-height: 42px;
}

.dict-name {
  background: #f2f3f5;
  border-radius: 2px;
  color: #1d2129;
  padding: 5px 8px;
  display: inline-block;
  margin: 4px;
}

.food-sub-name {
  font-size: 14px;
  color: #1d2129;
}
.food-weight {
  color: #165dff;
  cursor: pointer;
}

.dict-del-icon {
  font-size: 12px;
  color: #4e5969;
  cursor: pointer;
  margin-left: 4px;
}

.dict-btn {
  cursor: pointer;
  background: #e8f3ff;
  color: #165dff;
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
}

.season-row {
  margin-bottom: 12px;
}

.season-item {
  background: #f7f8fa;
  border-radius: 100px 100px 100px 100px;
  font-size: 14px;
  color: #4e5969;
  padding: 5px 16px;
  margin-right: 16px;
  cursor: pointer;
}

.season-item-active {
  background: #e8f3ff;
  color: #165dff;
}

.week-row {
  margin-bottom: 12px;
  display: flex;
}

.week-item {
  color: #4e5969;
  cursor: pointer;
}

.week-item-active {
  color: #165dff;
}

.icon-add {
  margin-left: 4px;
}

.diet-info-box {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.diet-info {
  font-weight: 400;
  font-size: 14px;
  color: #4e5969;
  margin-right: 12px;
}

.diet-all {
  font-size: 14px;
  color: #1d2129;
  font-weight: 500;
}

.diet-num-normal {
  color: #00b42a;
}

.diet-num-warn {
  color: #ff7d00;
}

.diet-num-danger {
  color: #f53f3f;
}
</style>
